package org.dualr.litelog.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dualr.litelog.dao.CategoryDao;
import org.dualr.litelog.dao.CommentDao;
import org.dualr.litelog.dao.LinkDao;
import org.dualr.litelog.dao.PostDao;
import org.dualr.litelog.dao.TagDao;
import org.dualr.litelog.entity.Category;
import org.dualr.litelog.entity.Comment;
import org.dualr.litelog.entity.Link;
import org.dualr.litelog.entity.Page;
import org.dualr.litelog.entity.Post;
import org.dualr.litelog.entity.Tag;
import org.dualr.litelog.utils.LiteLogUtil;

@SuppressWarnings("serial")
public class IndexServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		//
		List<Category> categoryList = CategoryDao.getInstance().getListByProperty("type", "post", "string");
		req.setAttribute("categoryList", categoryList);
		//tag
		List<Tag> tagList = TagDao.getInstance().getAll();
		req.setAttribute("tagList", tagList);
		//
		List<Link> linkList = LinkDao.getInstance().getAll();
		req.setAttribute("linkList", linkList);
		//
		List<Post> popPostList = PostDao.getInstance().getPopPost(0, 6);
		req.setAttribute("PopPostList", popPostList);
		//
		List<Comment> recentCommentList = CommentDao.getInstance().getCommentByRange(0, 6);
		req.setAttribute("RecentCommentList", recentCommentList);
		//
		int hits;
		hits = PostDao.getInstance().getCountByPropertyStatus("all", "", "publish");
		int curPage = 1;
		if (req.getParameter("page") != null
				&& !"".equals(req.getParameter("page"))) {
			curPage = Integer.parseInt(req.getParameter("page"));
		}
		int pageSize = 6;
		Page page = LiteLogUtil.getInstance().pager(hits, pageSize, curPage);
		int indexStart = (curPage - 1) * pageSize;
		int indexEnd = curPage * pageSize;
		List<Post> postList = PostDao.getInstance().getPostByStatusRange(indexStart, indexEnd, "publish");
		req.setAttribute("PostList", postList);
		req.setAttribute("Page", page);
		req.setAttribute("pageMethod", "list");
		req.setAttribute("param", "list");
		try {
			req.getRequestDispatcher("index.jsp").forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
